package com.gzc.just.play.last.war.sceneserver.ai;

import com.gzc.just.play.last.war.sceneserver.gameobject.unit.GameUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择器节点 - 执行第一个成功的子节点
 * 
 * 映射自C++ SelectorNode
 * 会依次执行子节点，直到某个子节点返回SUCCESS或RUNNING
 * 
 * @author AI编程助手
 * @version 1.0
 */
public class SelectorNode extends BehaviorNode {
    
    private List<BehaviorNode> children = new ArrayList<>();
    private int currentChildIndex = 0;
    
    /**
     * 构造函数
     * 
     * @param name 节点名称
     */
    public SelectorNode(String name) {
        super(name, NodeType.SELECTOR);
    }
    
    /**
     * 添加子节点
     * 
     * @param child 子节点
     */
    public void addChild(BehaviorNode child) {
        if (child != null) {
            children.add(child);
        }
    }
    
    /**
     * 移除子节点
     * 
     * @param child 子节点
     */
    public void removeChild(BehaviorNode child) {
        children.remove(child);
    }
    
    /**
     * 获取所有子节点
     * 
     * @return 子节点列表
     */
    public List<BehaviorNode> getChildren() {
        return new ArrayList<>(children);
    }
    
    @Override
    public Result tick(GameUnit unit, long deltaTime) {
        // 如果没有子节点，返回失败
        if (children.isEmpty()) {
            lastResult = Result.FAILURE;
            return lastResult;
        }
        
        // 从当前子节点开始执行
        for (int i = currentChildIndex; i < children.size(); i++) {
            BehaviorNode child = children.get(i);
            Result childResult = child.tick(unit, deltaTime);
            
            // 如果子节点成功或运行中，更新当前索引并返回结果
            if (childResult == Result.SUCCESS || childResult == Result.RUNNING) {
                currentChildIndex = i;
                lastResult = childResult;
                return lastResult;
            }
            // 如果子节点失败，继续执行下一个子节点
        }
        
        // 所有子节点都失败
        currentChildIndex = 0;
        lastResult = Result.FAILURE;
        return lastResult;
    }
    
    @Override
    public void initialize(GameUnit unit) {
        super.initialize(unit);
        currentChildIndex = 0;
        for (BehaviorNode child : children) {
            child.initialize(unit);
        }
    }
    
    @Override
    public void terminate(GameUnit unit) {
        super.terminate(unit);
        for (BehaviorNode child : children) {
            child.terminate(unit);
        }
        currentChildIndex = 0;
    }
}
